#pragma once
#include "Socket.hpp"
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>
#include <functional>

using namespace SocketModule;

class Requst
{

public:
    Requst(int x, int y, char oper)
        : _x(x), _y(y), _oper(oper)
    {
    }

    Requst()
    {
    }

    ~Requst()
    {
    }

    // 使用Json进行序列化处理
    std::string Serialize()
    {
        Json::Value root;
        root["x"] = _x;
        root["y"] = _y;
        root["oper"] = _oper;

        Json::FastWriter writer;
        std::string s = writer.write(root);
        return s;
    }

    // 使用Json进行反序列化处理
    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
        }

        return ok;
    }

    int X() { return _x; }
    int Y() { return _y; }
    char Oper() { return _oper; }

private:
    int _x;
    int _y;
    char _oper;
};

class Response
{

public:
    Response()
    {
    }
    Response(int result, int code)
        : _result(result), _code(code)
    {
    }

    ~Response()
    {
    }

    std::string Serialize()
    {
        Json::Value root;
        root["result"] = _result;
        root["code"] = _code;

        Json::FastWriter writer;
        return writer.write(root);
    }

    bool Deserialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;
        bool ok = reader.parse(in, root);
        if (ok)
        {
            _result = root["result"].asInt();
            _code = root["code"].asInt();
        }

        return ok;
    }

    void setResult(int res)
    {
        _result = res;
    }

    void SetCode(int code)
    {
        _code = code;
    }

    void ShowResult()
    {
        std::cout << "计算的结果是:" << _result << "[" << _code << "]" << std::endl;
    }

private:
    int _result;
    int _code;
};

const std::string sep = "\r\n";

using func_t = std::function<Response(Requst &req)>;

// 进行格式化处理类
class Protocol
{

public:
    Protocol()
    {
    }
    Protocol(func_t func)
        : _func(func)
    {
    }

    ~Protocol()
    {
    }

    // 封装报头
    std::string Ecode(const std::string &jsonstr)
    {
        std::string len = std::to_string(jsonstr.size());
        return len + sep + jsonstr + sep;
    }

    // 将报文当中的报头去除,并将一条序列化数据提取出来
    bool Decode(std::string &buffer, std::string *package)
    {
        ssize_t pos = buffer.find(sep);
        if (pos == std::string::npos)
        {
            return false;
        }
        std::string package_len_str = buffer.substr(0, pos);
        int package_len_int = std::stoi(package_len_str);
        int target_len = package_len_str.size() + package_len_int + 2 * sep.size();
        if (target_len > buffer.size())
        {
            return false;
        }
        *package = buffer.substr(pos + sep.size(), package_len_int);
        buffer.erase(0, target_len);
        return true;
    }

    void GetRequst(std::shared_ptr<Socket> &sock, InetAddr &client)
    {
        std::string buffer_queue;
        while (1)
        {
            int n = sock->Recv(&buffer_queue);
            if (n > 0)
            {
                std::cout << "---------requst_buffer------------" << std::endl;
                std::cout << buffer_queue << std::endl;
                std::cout << "----------------------------------" << std::endl;

                std::string json_package;
                // 给数据去除报头
                while (Decode(buffer_queue, &json_package))
                {
                    std::cout << "---------requst_json------------" << std::endl;
                    std::cout << json_package << std::endl;
                    std::cout << "----------------------------------" << std::endl;
                    std::cout << "---------requst_buffer------------" << std::endl;
                    std::cout << buffer_queue << std::endl;
                    std::cout << "----------------------------------" << std::endl;
                    LOG(LogLevel::DEBUG) << client.StringAddr() << "请求:" << json_package;
                    Requst req;
                    // 对报文进行反序列化处理
                    bool ok = req.Deserialize(json_package);
                    if (!ok)
                    {
                        continue;
                    }
                    // 进行计算
                    Response resp = _func(req);
                    // 将计算的结果序列化
                    std::string json_str = resp.Serialize();
                    // 将结果添加报头
                    std::string send_str = Ecode(json_str);
                    // 进行发送
                    sock->Send(send_str);
                }
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client:" << client.StringAddr() << "Quit";
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "client:" << client.StringAddr() << " recv error";
                break;
            }
        }
    }

    bool GetResponse(std::shared_ptr<Socket> &client, std::string &resp_buff, Response *resp)
    {
        while (1)
        {
            int n = client->Recv(&resp_buff);
            if (n > 0)
            {
                std::string json_package;
                bool ret = Decode(resp_buff, &json_package);
                if (!ret)
                    continue;
                std::cout << "---------requst_json------------" << std::endl;
                std::cout << json_package << std::endl;
                std::cout << "----------------------------------" << std::endl;
                std::cout << "---------requst_buffer------------" << std::endl;
                std::cout << resp_buff << std::endl;
                std::cout << "----------------------------------" << std::endl;

                resp->Deserialize(json_package);
                return true;
            }
            else if (n == 0)
            {
                std::cout << "Server quit" << std::endl;
                return false;
            }
            else
            {
                std::cout << "recv erroe" << std::endl;
                return false;
            }
        }
    }

    std::string BuildRequeString(int x, int y, char oper)
    {
        Requst req(x, y, oper);
        std::string json_req = req.Serialize();
        std::cout << "---------requst_json------------" << std::endl;
        std::cout << json_req << std::endl;
        std::cout << "----------------------------------" << std::endl;

        return Ecode(json_req);
    }

private:
    func_t _func;
};